package com.v1.video.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.MainPageNewActivity;
import com.v1.video.activity.MediaStoreVideoList;
import com.v1.video.db.dao.ThemeTB;
import com.v1.video.domain.OptionInfo;
import com.v1.video.interfaces.OnVideoCameraListener;
import com.v1.video.view.CustomActionSheetDialog;
import com.v1.video.view.CustomActionSheetDialog.OnActionSheetItemClick;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Utils {

    private static final String TAG = "Utils";

    public static MainPageNewActivity mainPageActivity = null;

    private Utils () {
    }

    public static int getDisplayRotation (Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        switch (rotation) {
            case Surface.ROTATION_0:
                return 0;
            case Surface.ROTATION_90:
                return 90;
            case Surface.ROTATION_180:
                return 180;
            case Surface.ROTATION_270:
                return 270;
        }
        return 0;
    }

    public static int getDisplayOrientation (int degrees, int cameraId) {
        // See android.hardware.Camera.setDisplayOrientation for
        // documentation.
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    public static boolean sdcardAvailable () {
        String state = Environment.getExternalStorageState();
        Log.d(TAG, "Environment.getExternalStorageState() : " + state);
        if (Environment.MEDIA_MOUNTED.equals(state))
            return true;
        else
            return false;
    }

    public static void echoCursor (Cursor cursor) {
        String format = "%d    %s : %s";
        int count = cursor.getColumnCount();
        while (cursor.moveToNext()) {
            for (int columnIndex = 0; columnIndex < count; columnIndex++) {

                String columnName = cursor.getColumnName(columnIndex);
                String value = cursor.getString(columnIndex);
                Log.d(TAG,
                        String.format(format, columnIndex, columnName, value));
            }
        }
    }

    public static DisplayMetrics getScreenInfo (Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }

    public static int calculateInSampleSize (Options options, int reqWidth,
                                             int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }

        return inSampleSize;
    }

    /**
     * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1
     *
     * @param c
     * @return
     */
    public static long calculateLength (CharSequence c) {
        double len = 0;
        for (int i = 0; i < c.length(); i++) {
            int tmp = (int) c.charAt(i);
            if (tmp > 0 && tmp < 127) {
                len += 0.5;
            } else {
                len++;
            }
        }
        return Math.round(len);
    }

    public static void showToast (Context context, String str, int duration) {
        Toast toast = new Toast(context);
        View view = View.inflate(context, R.layout.toast, null);
        TextView tv = (TextView) view.findViewById(R.id.tv);
        tv.setText(str);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(duration);
        toast.show();

    }

    public static Toast showtoast (Context context, String str, int duration) {
        Toast toast = new Toast(context);
        View view = View.inflate(context, R.layout.toast, null);
        TextView tv = (TextView) view.findViewById(R.id.tv);
        tv.setText(str);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(duration);
        toast.show();
        return toast;

    }

	/*
     * public static ImageFetcher getImageFetcher(FragmentActivity activity) {
	 * final String IMAGE_CACHE_DIR = "thumbs";
	 * 
	 * DisplayMetrics outMetrics = new DisplayMetrics();
	 * activity.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
	 * 
	 * ImageCacheParams cacheParams = new ImageCacheParams(activity,
	 * IMAGE_CACHE_DIR);
	 * 
	 * cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of
	 * app memory
	 * 
	 * // The ImageFetcher takes care of loading images into our ImageView
	 * children asynchronously ImageFetcher mImageFetcher = new
	 * ImageFetcher(activity, outMetrics.widthPixels / 3);
	 * mImageFetcher.setLoadingImage(R.drawable.empty_photo);
	 * mImageFetcher.addImageCache(activity.getSupportFragmentManager(),
	 * cacheParams); // mImageFetcher.clearCache();
	 * 
	 * 
	 * return mImageFetcher; }
	 */

    public static String parseTime (long milliseconds) {
        milliseconds /= 1000;
        long m = milliseconds / 60;
        long s = milliseconds % 60;

        String parseTime = (m < 10 ? ("0" + m) : m) + ":"
                + (s < 10 ? ("0" + s) : s);
        return parseTime;
    }

    /**
     * 从view 得到图片
     *
     * @param view
     * @return
     */
    public static Bitmap getBitmapFromView (View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache(true);
        return bitmap;
    }

    public static String millisToString (int millis) {
        millis /= 1000;
        int minute = millis / 60;
        int hour = minute / 60;
        int second = millis % 60;
        minute %= 60;
        if (hour > 0) {
            return String.format("%02d:%02d:%02d", hour, minute, second);
        } else {
            return String.format("%02d:%02d", minute, second);
        }
    }

    // public static void displayImage(String uri, ImageView iv,
    // DisplayImageOptions imageOptions){
    // if( uri.endsWith(".jpg")||
    // uri.endsWith(".JPG")||
    // uri.endsWith(".png")||
    // uri.endsWith(".PNG")||
    // uri.endsWith(".jpeg")||
    // uri.endsWith(".JPEG")){
    // ImageLoader.getInstance().displayImage("file://" + uri, iv,
    // imageOptions);
    // }else if(uri.endsWith(".mp4")){
    // ImageLoader.getInstance().displayImage("thumb://" + uri, iv,
    // imageOptions);
    //
    // }
    // }
    public static CustomProgressDialog getProgressDialog (Context context,
                                                          final AsyncTask asyncTask) {
        return getProgressDialog(context, "正在加载数据……", asyncTask);
    }

    public static CustomProgressDialog getProgressDialog (Context context,
                                                          String message, final AsyncTask asyncTask) {
        // ProgressDialog pg = new ProgressDialog(context);
        // pg.setMessage(message);
        CustomProgressDialog pg = new CustomProgressDialog(context,
                R.style.style_Custom_ProgressDialog, message);
        pg.setCanceledOnTouchOutside(false);
        pg.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel (DialogInterface dialog) {
                if (asyncTask != null
                        && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
                    asyncTask.cancel(true);
                }
            }
        });
        pg.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey (DialogInterface dialog, int keyCode,
                                  KeyEvent event) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        Logger.i(TAG, "1111111111111111");
                        if (asyncTask != null
                                && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
                            asyncTask.cancel(true);
                            dialog.cancel();
                        }
                }
                return false;
            }
        });
        return pg;
    }

    public static CustomProgressDialog getProgressDialog (Context context,
                                                          String message) {
        CustomProgressDialog pg = new CustomProgressDialog(context,
                R.style.style_Custom_ProgressDialog, message);
        pg.setCanceledOnTouchOutside(false);
        pg.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel (DialogInterface dialog) {
                dialog.cancel();
            }
        });
        pg.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey (DialogInterface dialog, int keyCode,
                                  KeyEvent event) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        Logger.i(TAG, "1111111111111111");
                        dialog.cancel();
                }
                return false;
            }
        });
        return pg;
    }

    /**
     * 保存频道信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveChannelToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.CHANNEL_FILENAME);
    }

    /**
     * 保存头条信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveHeadLineToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.HEADLINE_FILENAME);
    }

    /**
     * 订阅按时间的信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveSubscribeTimeToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.SUBSCRIBE_TIME_FILENAME);
    }

    /**
     * 保存看到信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveSeeListToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.SEE_FILENAME);
    }

    /**
     * 将数据保存的文件中,会覆盖以前的数据，如果文件存在先删除，然后在重新创建
     *
     * @param context
     * @param saveStr
     * @param fileName
     */
    public static void saveInfoToFile (Context context, String saveStr,
                                       String fileName) {
        File file = new File(context.getFilesDir(), fileName);

        if (file != null && file.exists()) {
            file.delete();
        }
        BufferedWriter writer = null;
        try {
            file.createNewFile();
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(saveStr);
            writer.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 订阅精选的信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveSubscribeSelectionToFile (Context context,
                                                     String saveStr) {
        saveInfoToFile(context, saveStr, Constant.SUBSCRIBE_SELECTION_FILENAME);
    }

    /**
     * 订阅我的订阅的信息
     *
     * @param context
     * @param saveStr
     */
    public static void saveSubscribeMyToFile (Context context, String saveStr,
                                              String key) {
        saveInfoToFile(context, saveStr, Constant.SUBSCRIBE_MY_FILENAME + "_"
                + key);
    }

//    public static List<VideoInfo4> getSubscribeSelectionInfoFromFile (
//            Context context) {
//        File file = new File(context.getFilesDir(),
//                Constant.SUBSCRIBE_SELECTION_FILENAME);
//        if (file.exists()) {
//            InputStream inputStream = null;
//            BufferedReader in = null;
//            String jsonMessage = null;
//            try {
//                inputStream = new FileInputStream(file);
//                in = new BufferedReader(new InputStreamReader(inputStream));
//                jsonMessage = in.readLine();
//                Type listType = new TypeToken<List<VideoInfo4>>() {
//                }.getType();
//                Gson gson = new Gson();
//                return gson.fromJson(jsonMessage, listType);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//                return null;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        } else {
//            return null;
//        }
//    }

//    public static List<SubscribeMyObj> getSubscribeMyInfoFromFile (
//            Context context, String key) {
//        File file = new File(context.getFilesDir(),
//                Constant.SUBSCRIBE_MY_FILENAME + "_" + key);
//        if (file.exists()) {
//            InputStream inputStream = null;
//            BufferedReader in = null;
//            String jsonMessage = null;
//            try {
//                inputStream = new FileInputStream(file);
//                in = new BufferedReader(new InputStreamReader(inputStream));
//                jsonMessage = in.readLine();
//                Type listType = new TypeToken<List<SubscribeMyObj>>() {
//                }.getType();
//                Gson gson = new Gson();
//                return gson.fromJson(jsonMessage, listType);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//                return null;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        } else {
//            return null;
//        }
//    }

//    public static List<VideoInfo4> getSubscribeTimeInfoFromFile (Context context) {
//        File file = new File(context.getFilesDir(),
//                Constant.SUBSCRIBE_TIME_FILENAME);
//        if (file.exists()) {
//            InputStream inputStream = null;
//            BufferedReader in = null;
//            String jsonMessage = null;
//            try {
//                inputStream = new FileInputStream(file);
//                in = new BufferedReader(new InputStreamReader(inputStream));
//                jsonMessage = in.readLine();
//                Type listType = new TypeToken<List<VideoInfo4>>() {
//                }.getType();
//                Gson gson = new Gson();
//                return gson.fromJson(jsonMessage, listType);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//                return null;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        } else {
//            return null;
//        }
//    }

    public static List<ThemeTB> getThemeAllThemeInfoFromFile (Context context,
                                                              String key) {
        File file = new File(context.getFilesDir(),
                Constant.THEME_ALL_THEME_FILENAME + "_" + key);
        if (file.exists()) {
            InputStream inputStream = null;
            BufferedReader in = null;
            String jsonMessage = null;
            try {
                inputStream = new FileInputStream(file);
                in = new BufferedReader(new InputStreamReader(inputStream));
                jsonMessage = in.readLine();
                Type listType = new TypeToken<List<ThemeTB>>() {
                }.getType();
                Gson gson = new Gson();
                return gson.fromJson(jsonMessage, listType);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } else {
            return null;
        }
    }

//    /**
//     * 获取请愿列表信息
//     *
//     * @param context
//     * @return
//     */
//    public static List<PetitionInfo> getStarPetitionListInfoFromFile (Context context) {
//        File file = new File(context.getFilesDir(),
//                Constant.STAR_PETITION_LIST_INFO);
//        if (file.exists()) {
//            InputStream inputStream = null;
//            BufferedReader in = null;
//            String jsonMessage = null;
//            try {
//                inputStream = new FileInputStream(file);
//                in = new BufferedReader(new InputStreamReader(inputStream));
//                jsonMessage = in.readLine();
//                Type listType = new TypeToken<List<PetitionInfo>>() {
//                }.getType();
//                Gson gson = new Gson();
//                return gson.fromJson(jsonMessage, listType);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        } else {
//            return null;
//        }
//    }

//    /**
//     * 获取网红信息
//     *
//     * @param context
//     * @return
//     */
//    public static List<StarInfo> getStarInfoFromFile (Context context) {
//        File file = new File(context.getFilesDir(),
//                Constant.STAR_LIST_INFO);
//        if (file.exists()) {
//            InputStream inputStream = null;
//            BufferedReader in = null;
//            String jsonMessage = null;
//            try {
//                inputStream = new FileInputStream(file);
//                in = new BufferedReader(new InputStreamReader(inputStream));
//                jsonMessage = in.readLine();
//                Type listType = new TypeToken<List<StarInfo>>() {
//                }.getType();
//                Gson gson = new Gson();
//                return gson.fromJson(jsonMessage, listType);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        } else {
//            return null;
//        }
//    }

    /**
     * 网红：请愿列表
     *
     * @param context
     * @param saveStr
     */
    public static void saveStarsPetitionInfoToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.STAR_PETITION_LIST_INFO);
    }

    /**
     * 网纸：明星列表
     *
     * @param context
     * @param saveStr
     */
    public static void saveStarsInfoToFile (Context context, String saveStr) {
        saveInfoToFile(context, saveStr, Constant.STAR_LIST_INFO);
    }

    /**
     * 主题：全部主题
     *
     * @param context
     * @param saveStr
     */
    public static void saveThemeAllToFile (Context context, String saveStr,
                                           String key) {
        saveInfoToFile(context, saveStr, Constant.THEME_ALL_THEME_FILENAME
                + "_" + key);
    }

    /**
     * 毫秒值解析成固定日期格式数据"yyyy-MM-dd HH:mm:ss"
     *
     * @param timeInMillis
     * @return
     */
    public static String getParseTime (long timeInMillis) {
        String parsedate = null;
        try {
            SimpleDateFormat simpledateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.setTimeInMillis(timeInMillis);
            parsedate = simpledateFormat.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parsedate;
    }

    /**
     * 毫秒值解析成固定日期格式数据"yyyy-MM-dd HH:mm:ss"
     *
     * @param timeInMillis
     * @return
     */
    public static String getParseTime (long timeInMillis, String formate) {
        String parsedate = null;
        try {
            SimpleDateFormat simpledateFormat = new SimpleDateFormat(formate);
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.setTimeInMillis(timeInMillis);
            parsedate = simpledateFormat.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parsedate;
    }

    /**
     * 固定格式化日期 "yyyy-MM-dd HH:mm:ss"
     *
     * @param date
     * @return
     */
    public static String getFormatTime (String date) {
        return getFormatTime(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 固定格式化日期 "yyyy-MM-dd HH:mm:ss"
     *
     * @param date
     * @return
     */
    public static String getFormatTimeDate (String date) {
        String dateformat = "yyyy-MM-dd HH:mm:ss";
        if (date == null || date == "" || date.equals("")
                || date.equals("null")) {
            return "";
        }
        SimpleDateFormat simpledateFormat = new SimpleDateFormat(dateformat);
        String dataStr = "";
        try {
            Date parse = simpledateFormat.parse(date);
            // dataStr = parse.getDate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataStr;
    }

    /**
     * 指定日期格式，格式化日期
     *
     * @param date
     * @param dateformat
     * @return
     */
    public static String getFormatTime (String date, String dateformat) {

        String result;
        try {
            SimpleDateFormat simpledateFormat = new SimpleDateFormat(dateformat);
            Date parse = simpledateFormat.parse(date);
            Logger.i(TAG, "parse.getTime()==" + parse.getTime());
            long timeInterval = Calendar.getInstance().getTimeInMillis()
                    - parse.getTime();
            if (timeInterval < 60000) {
                result = "刚刚";
            } else if ((timeInterval = timeInterval / 60000) < 60) {
                result = timeInterval + "分钟前";
            } else if ((timeInterval = timeInterval / 60) < 24) {
                result = timeInterval + "小时前";
            } else if ((timeInterval = timeInterval / 24) < 30) {
                result = timeInterval + "天前";
            } else if ((timeInterval = timeInterval / 30) < 12) {
                result = timeInterval + "个月前";
            } else {
                timeInterval = timeInterval / 12;
                result = timeInterval + "年前";
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 指定日期格式，格式化日期
     *
     * @param time
     * @return
     */
    public static String getFormatTime (long time) {

        String result;
        try {

            long timeInterval = Calendar.getInstance().getTimeInMillis() - time;
            if (timeInterval < 60000) {
                result = "刚刚";
            } else if ((timeInterval = timeInterval / 60000) < 60) {
                result = timeInterval + "分钟前";
            } else if ((timeInterval = timeInterval / 60) < 24) {
                result = timeInterval + "小时前";
            } else if ((timeInterval = timeInterval / 24) < 30) {
                result = timeInterval + "天前";
            } else if ((timeInterval = timeInterval / 30) < 12) {
                result = timeInterval + "个月前";
            } else {
                timeInterval = timeInterval / 12;
                result = timeInterval + "年前";
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 图片转换成圆形
     */
    public static Bitmap toRoundBitmap (Bitmap bitmap) {
        if (bitmap == null)
            return null;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;

            left = 0;
            top = 0;
            right = width;
            bottom = width;

            height = width;

            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;

            float clip = (width - height) / 2;

            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;

            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right,
                (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top,
                (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);// 设置画笔无锯齿

        canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas

        // 以下有两种方法画圆,drawRounRect和drawCircle
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);//
        // 画圆角矩形，第一个参数为图形显示区域，第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(
                android.graphics.PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
        canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle

        return output;
    }

    /**
     * 百度推送相关的东西
     */
    public static String logStringCache = "";

    // 获取ApiKey
    public static String getMetaValue (Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true，unBind且成功时设置false
    public static boolean hasBind (Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        String flag = sp.getString("bind_flag", "");
        if ("ok".equalsIgnoreCase(flag)) {
            return true;
        }
        return false;
    }

    public static void setBind (Context context, boolean flag) {
        String flagStr = "not";
        if (flag) {
            flagStr = "ok";
        }
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sp.edit();
        editor.putString("bind_flag", flagStr);
        editor.commit();
    }

    /** 百度推送相关的东西 */

    /**
     * 得到设备屏幕的宽度
     */
    public static int getScreenWidth (Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 得到设备屏幕的高度
     */
    public static int getScreenHeight (Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 得到设备的密度
     */
    public static float getScreenDensity (Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * dip转换px
     */
    public static int dip2px (Context context, float px) {
        final float scale = getScreenDensity(context);
        return (int) (px * scale + 0.5f);
    }

    /**
     * px转换dip
     */
    public static int px2dip (Context context, float pxValue) {
        final float scale = getScreenDensity(context);
        return (int) (pxValue / scale + 0.5f);
    }

    public static void showFloatToast (Context context, String str) {
        Toast toast = new Toast(context);
        View view = View.inflate(context, R.layout.top_success_lay, null);
        TextView tv = (TextView) view.findViewById(R.id.textView1);
        tv.setText(str);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.show();

    }

    /**
     * 计算当前时间到目标时间的剩余时间
     *
     * @param aimDate 目标时间
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String computeDateDifference (String aimDate) {
        String result = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            Date aimdt = format.parse(aimDate);
            long ms = aimdt.getTime() - new Date().getTime();
            if (ms > 0) {
                long seconds = ms / 1000 % 60;
                long minutes = ms / (60 * 1000) % 60;
                long hours = ms / (60 * 60 * 1000) % 24;
                long days = ms / (24 * 60 * 60 * 1000);
                result = "还剩" + days + "天";
                if (hours < 10) {
                    result += "0" + hours;
                } else {
                    result += hours;
                }
                if (minutes < 10) {
                    result += ":0" + minutes;
                } else {
                    result += ":" + minutes;
                }
                if (seconds < 10) {
                    result += ":0" + seconds;
                } else {
                    result += ":" + seconds;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 计算16:9的图片高度
     *
     * @param context
     * @return
     */
    public static int computeImageHeight (Context context) {
        return computeImageHeight(context, 0, 1);
    }

    /**
     * 计算16:9的图片高度
     *
     * @param context
     * @param padding
     * @return
     */
    public static int computeImageHeight (Context context, int padding) {
        return computeImageHeight(context, padding, 1);
    }

    /**
     * 计算16:9的图片高度
     *
     * @param context
     * @param padding
     * @param count
     * @return
     */
    public static int computeImageHeight (Context context, int padding, int count) {
        int mWidth = Utils.getScreenWidth(context);
        BigDecimal b = new BigDecimal(((mWidth - padding) / count) * 9 / 16);
        int height = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return height;
    }

    /**
     * 计算16:9的图片宽度
     *
     * @param context
     * @param padding
     * @param count
     * @return
     */
    public static int computeImageWidth (Context context, int padding, int count) {
        int mWidth = Utils.getScreenWidth(context);
        BigDecimal b = new BigDecimal((mWidth - padding) / count);
        int width = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return width;
    }

    /**
     * 计算16:5的图片高度
     *
     * @param context
     * @return
     */
    public static int computeImageHeight_16_5 (Context context) {
        int mWidth = Utils.getScreenWidth(context);
        int height = mWidth * 5 / 16;
        return height;
    }

    /**
     * 计算27:13的图片高度
     *
     * @param context
     * @return
     */
    public static int computeImageHeight_27_13 (Context context) {
        int mWidth = Utils.getScreenWidth(context);
        int height = mWidth * 13 / 27;
        return height;
    }

    // /**我的订阅页，一页需放三个视频，算宽，两边各留 15，中间差8个像素*/
    // public static int computeImageWidthTo3(Context context){
    // int mWidth = getScreenWidth(context);
    // int left = dip2px(context, 15);//两边距
    // int w = dip2px(context, 8);//中间距
    // mWidth = (mWidth-left-left-w-w) / 3;
    // return mWidth;
    // }

    /**
     * 我的订阅页，一页需放三个视频，算宽，两边各留 15，中间差8个像素
     */
    public static int computeImageWidthTo3 (Context context) {
        int mWidth = getScreenWidth(context);
        // int left = dip2px(context, 15);//两边距
        int left = (int) context.getResources().getDimension(
                R.dimen.theme_img_left_right_bian);
        int w = (int) context.getResources().getDimension(
                R.dimen.theme_img_jianju);// dip2px(context, 8);//中间距
        mWidth = (mWidth - left - left - w - w) / 3;
        return mWidth;
    }

    /***
     * 计算图片的宽度 根据屏幕宽 减去两边的边距
     * @param context
     * @return
     */
    public static int computeImageWidth (Context context) {
        int mWidth = getScreenWidth(context);
//		int left = dip2px(context, 15);//两边距
        int left = (int) context.getResources().getDimension(R.dimen.person_info_left);
        mWidth = mWidth - left - left;
        return mWidth;
    }

    /***
     * 计算图片的宽度 :明星聚合页图片宽度
     * @param context
     * @return
     */
    public static int computeImageWidthStar (Context context) {
        int mWidth = getScreenWidth(context);
//		int left = dip2px(context, 15);//两边距
        float left = context.getResources().getDimension(R.dimen.padding_info_left);
        mWidth = (int) ((mWidth - left - left - left) / 2);
        return mWidth;
    }

    /**
     * 根据已知宽，按16：9计算高
     */
    public static int computeImageHeightWithWidth (int mWidth) {
        BigDecimal b = new BigDecimal(mWidth * 9 / 16);
        int height = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return height;
    }

    public static int computeHeight (float mHeight) {
        BigDecimal b = new BigDecimal(mHeight);
        int height = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return height;
    }

    public static int computeWidth (float mWidth) {
        BigDecimal b = new BigDecimal(mWidth);
        int width = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return width;
    }

    /**
     * 根据已知宽，按比例计算高
     *
     * @param mWidth
     * @param w      已知图片的宽
     * @param h      已知图片的高
     * @return
     */
    public static int computeImageHeightWithWidth (int mWidth, int w, int h) {
        BigDecimal b = new BigDecimal(mWidth * h / w);
        int height = (int) b.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
        return height;
    }

    public static boolean isCanPlay (Context mContext) {

        OptionInfo optionInfo = OptionInfo.getInstance(mContext);
        if (Helper.isWifi(mContext)) {
            if (optionInfo.isVideoDetailPageAutoPlay()) {
                return true;
            }
            if (optionInfo.isVideoAutoPlayAny()) {
                return true;
            } else {
                return false;
            }
        } else {
            // if(optionInfo.isVideoDetailPageAutoPlay()){
            // Logger.i(TAG, "44444444444444444444444");
            // return false;
            // }
            if (optionInfo.isVideoAutoPlayAny()) {
                return true;
            } else {
                return false;
            }
        }
    }

    /***
     * 是否可以 上传
     *
     * @return
     */
    public static boolean isCanUpload (Context mContext) {
        if (Helper.isWifi(mContext)) {
            return true;
        } else {
            OptionInfo optionInfo = OptionInfo.getInstance(mContext);
            if (optionInfo.isUploadAny()) {
                return true;
            } else {
                return false;
            }
        }
    }

    private static CustomActionSheetDialog mCasdialog;

    /**
     * 弹出视频菜单
     *
     * @param mContext
     * @param mOnVideoCameraListener
     */
    public static void showVideoCameraSheet (final Context mContext,
                                             final OnVideoCameraListener mOnVideoCameraListener) {
        // if (mCasdialog == null) {
        if (mCasdialog != null) {
            mCasdialog.dismiss();
            mCasdialog = null;
        }
        Resources res = mContext.getResources();
        mCasdialog = new CustomActionSheetDialog(mContext, new String[]{
                res.getString(R.string.video_record_action_sheet_select_local),
                res.getString(R.string.video_record_action_sheet_video)});
        mCasdialog.setOnActionSheetItemClick(new OnActionSheetItemClick() {

            @Override
            public void onClick (int index, String actionName) {
                mCasdialog.dismiss();
                mCasdialog = null;
                switch (index) {
                    case 0:
                        // Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                        // intent2.setType("video/*");
                        // intent2.setDataAndType(
                        // MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        // "video/*");
                        Intent intent2 = new Intent();
                        intent2.setClass(mContext, MediaStoreVideoList.class);
                        if (mOnVideoCameraListener != null) {
                            mOnVideoCameraListener.onVideoCamera(intent2,
                                    Constant.REQUEST_CODE_VIDEO_SELECT);
                        }
                        break;
                    case 1:
                        File destDir = new File(Environment
                                .getExternalStorageDirectory(), "/DCIM/Camera");
                        if (!destDir.exists()) {
                            destDir.mkdirs();
                        }
                        Uri uri = Uri.fromFile(new File(destDir, "VID_"
                                + System.currentTimeMillis() + ".mp4"));
                        ContentValues cv = new ContentValues();
                        cv.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
                        cv.put(MediaStore.Video.Media.DATA, uri.getPath());
                        Uri mUri = mContext.getContentResolver().insert(
                                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cv);
                        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                        if (mOnVideoCameraListener != null) {
                            mOnVideoCameraListener.onVideoCamera(intent,
                                    Constant.REQUEST_CODE_VIDEO_CAPTURE);
                        }
                        break;
                }
            }
        });
        // }
        mCasdialog.show();
    }

    public static String getRealFilePath (Context mContext, final Uri mUri) {
        if (null == mUri) {
            return null;
        }
        final String scheme = mUri.getScheme();
        String data = null;
        if (scheme == null)
            data = mUri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = mUri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = mContext.getContentResolver().query(mUri,
                    new String[]{ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 获取系统时间
     *
     * @return
     */
    public static long getSystemTime () {
        Date date = new Date();
        return date.getTime();
    }

    public static void saveChannelOperate (Context context, boolean value) {
        SharedPreferences preferences = context.getSharedPreferences("channel",
                Context.MODE_PRIVATE);
        Editor editor = preferences.edit();
        editor.putBoolean("operate", value);
        editor.commit();
    }

    public static boolean getChannelOperate (Context context) {
        SharedPreferences preferences = context.getSharedPreferences("channel",
                Context.MODE_PRIVATE);
        return preferences.getBoolean("operate", false);
    }

    public static String getShowTime (long milliseconds) {
        // 获取日历函数
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat dateFormat = null;
        // 判断是否大于60分钟，如果大于就显示小时。设置日期格式
        if (milliseconds / 60000 > 60) {
            dateFormat = new SimpleDateFormat("hh:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("00:mm:ss");
        }
        return dateFormat.format(calendar.getTime());
    }

    public static void startImageAnim (ImageView Img, int anim) {
        Img.setVisibility(View.VISIBLE);
        try {
            Img.setImageResource(anim);
            AnimationDrawable animationDrawable = (AnimationDrawable) Img
                    .getDrawable();
            animationDrawable.start();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }

    public static void stopImageAnim (ImageView Img) {
        try {
            AnimationDrawable animationDrawable = (AnimationDrawable) Img
                    .getDrawable();
            animationDrawable.stop();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        Img.setVisibility(View.GONE);
    }

    public static String getDeviceId (Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getDeviceId() != null) {
            return tm.getDeviceId();
        } else {
            return "";
        }
    }

    public static String getMacAddress (Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        if (info.getMacAddress() != null) {
            return info.getMacAddress();
        } else {
            return "";
        }
    }

    public static String getSubscriberId (Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getSubscriberId() != null) {
            return tm.getSubscriberId();
        } else {
            return "";
        }
    }

    public static Map<String, String> getLongitudeAndLatitude (Context context) {
        Map<String, String> map = null;
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                map = new HashMap<String, String>();
                map.put("latitude", location.getLatitude() + "");
                map.put("longitude", location.getLongitude() + "");
            }
        } else {
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 1000, 0,
                    new LocationListener() {

                        @Override
                        public void onStatusChanged (String provider,
                                                     int status, Bundle extras) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onProviderEnabled (String provider) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onProviderDisabled (String provider) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onLocationChanged (Location location) {
                            // TODO Auto-generated method stub
                            if (location != null) {
                                Logger.i("Map", "Location changed : Lat: "
                                        + location.getLatitude() + " Lng: "
                                        + location.getLongitude());
                            }
                        }
                    });
            Location location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                map = new HashMap<String, String>();
                map.put("latitude", location.getLatitude() + "");
                map.put("longitude", location.getLongitude() + "");
            }
        }
        return map;
    }

    public static String getProducted (Context context) {
        String productCode = "0101" + Util.getChanelId(context);
        return productCode;
    }

    public static String getRandomString (int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 小写字母
                val += (char) (97 + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 获取手机系统版本
     *
     * @return
     */
    public static String getPhoneOsVersion () {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 格式化日期
     *
     * @param timestamp
     * @return
     */
    public static String getTimeStampToFormatString (String timestamp, String pattern) {
        if (!TextUtils.isEmpty(timestamp)) {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            try {
                Calendar calendar = Calendar.getInstance();
                calendar.clear();
                calendar.setTimeInMillis(Long.parseLong(timestamp));
                return format.format(calendar.getTime());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }

    public static int getStatusBarHeight (Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
